package com.oj.util;

import com.oj.config.OJConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class JudgeUtil {

    public static int SendMsg2Judger(String ip, int port, int msgType, String cmdBuff) {
        Socket socket;
        try {
            /* Magic:0xabcddcba
             * TLV:  type=0x0001; length=strlen(cmdBuff); value=cmdBuff
             * TLV:  type=0x0002; length=strlen(test-json); value=test-json
             * */
            String encode = OJConfig.getEncode();
            if (encode == null) {
                encode = "UTF-8";
            }
            String reqStr = String.format("%s%04x%08x%s", "abcddcba",
                    msgType, cmdBuff.getBytes(encode).length, cmdBuff);
            log.info(encode + ": " + reqStr);
            socket = new Socket(ip, port);
            OutputStream outPutStream = socket.getOutputStream();
            outPutStream.write(reqStr.getBytes(encode));
            outPutStream.flush();
            socket.close();
            return 0;
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            log.error("SendMsg2Judger to ip:" + ip + " port:"+ port +" cmdBuff:"+cmdBuff+" , but failed.");
            //e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            log.error("SendMsg2Judger to ip:" + ip + " port:"+ port +" cmdBuff:"+cmdBuff+" , but connect failed.");
        }

        return 1;
    }

    public static int JudgeRequest(String ip, int port, Integer solutionId) {
        return SendMsg2Judger(ip, port, 0x0001, "judge solution "+ solutionId);
    }

    public static int JudgeTestRequest(String ip, int port, String json) {
        return SendMsg2Judger(ip, port, 0x0002, json);
    }
    public static int JudgeVerifyRequest(String ip, int port, String json) {
        return SendMsg2Judger(ip, port, 0x0002, json);
    }
}
